package masking.wechat.sdk.util;

import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JacksonUtils {

	private ObjectMapper objectMapper;

	private JacksonUtils(DateFormat sdf) {
		objectMapper = new ObjectMapper();

		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		objectMapper.setDateFormat(sdf);
	}

	public static JacksonUtils getInstance() {
		return new JacksonUtils(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}
	
	/**
	 * 获取泛型的Collection Type
	 * 
	 * @param collectionClass
	 *            泛型的Collection
	 * @param elementClasses
	 *            元素类
	 * @return JavaType Java类型
	 * @since 1.0
	 */
	public JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}

	public static JacksonUtils getInstance(DateFormat sdf) {
		if (sdf == null)
			return getInstance();
		else
			return new JacksonUtils(sdf);
	}

	public <T> T fromJson(String jsonString, Class<T> clazz)
			throws JsonParseException, JsonMappingException, IOException {
		if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		return objectMapper.readValue(jsonString, clazz);
	}
	
    public <T> T fromJson(String jsonString, JavaType valueType) throws JsonParseException, JsonMappingException, IOException {
    	if (StringUtils.isEmpty(jsonString)) {
			return null;
		}
		return objectMapper.readValue(jsonString, valueType);
    }


	public String toJson(Object object) throws JsonProcessingException {
		return objectMapper.writeValueAsString(object);
	}
	
	public JsonNode readTree(String jsonString) throws JsonProcessingException, IOException {
		return objectMapper.readTree(jsonString);
	}
}
